import 'dart:io';
import 'dart:isolate';
import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:management/utils/log_utils.dart';
import 'package:open_file/open_file.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';

/// https://www.jianshu.com/p/c5f005a2e8c8
/// https://pub.flutter-io.cn/packages/flutter_downloader
/// 版本信息
class VersionInfo extends StatefulWidget {
  @override
  _VersionInfoState createState() => _VersionInfoState();
}

class _VersionInfoState extends State<VersionInfo> {
  ReceivePort _port = ReceivePort();
  static String? versionName;
  static String? versionCode;

  @override
  void initState() {
    SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top]);
    SystemUiOverlayStyle systemUiOverlayStyle =
        SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);

    super.initState();

    PackageInfo.fromPlatform().then((value) {
      setState(() {
        versionName = value.version;
        versionCode = value.buildNumber;
      });
    });

    IsolateNameServer.registerPortWithName(
        _port.sendPort, 'downloader_send_port');
    _port.listen((dynamic data) {
      String id = data[0];
      DownloadTaskStatus status = data[1];
      int progress = data[2];
      if (status == DownloadTaskStatus.complete) {
        _installApk();
      }

      setState(() {});
    });

    FlutterDownloader.registerCallback(downloadCallback);
  }

  static void downloadCallback(
      String id, DownloadTaskStatus status, int progress) {
    final SendPort send =
        IsolateNameServer.lookupPortByName('downloader_send_port')!;
    send.send([id, status, progress]);
  }

  /// 获取apk存放地址(外部路径)
  static Future<String> get _apkLocalPath async {
    final directory = await getExternalStorageDirectory();
    return directory!.path;
  }

  ///安装app
  static Future<Null> _installApk() async {
    String path = await _apkLocalPath;
    await OpenFile.open(path + '/' + "app-release.apk");
  }

  /// 下载
  static Future<void> executeDownload() async {
    //apk存放路径
    final path = await _apkLocalPath;
    MyLog.i("path: $path");
    //获取版本
    var result = await Dio()
        .get("http://139.159.203.5:8080/apk/management/versionName")
        .catchError((e) {
      MyLog.e('获取版本号失败==》' + e.toString());
      Fluttertoast.showToast(msg: "获取版本号失败");
      return null;
    });
    if (result == null){
      return;
    }
    var replaceAll = result.toString().replaceAll("\n", "");
    MyLog.i("replaceAll: $replaceAll     versionName: $versionName");
    if (TextUtil.isEmpty(replaceAll)) {
      return;
    }
    if (replaceAll.compareTo(versionName!) <= 0) {
      Fluttertoast.showToast(msg: "无更新");
      return;
    }
    Fluttertoast.showToast(msg: "正在准备更新...");
    var apkName = 'app-release' + '.apk';
    File file = File(path + '/' + apkName);
    if (await file.exists()) await file.delete();

    //下载
    try {
      final taskId = await FlutterDownloader.enqueue(
          url:
              'http://139.159.203.5:8080/apk/management/$replaceAll/app-release.apk',
          //下载最新apk的网络地址
          savedDir: path,
          fileName: apkName,
          showNotification: true,
          openFileFromNotification: true);
    } on Exception catch (e) {
      MyLog.e(e.toString());
    }
  }

  @override
  void dispose() {
    IsolateNameServer.removePortNameMapping('downloader_send_port');
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.black,
            size: 35,
          ),
          onPressed: () {
            SystemChrome.setEnabledSystemUIOverlays([]);
            Navigator.pop(context);
          },
        ),
        backgroundColor: Colors.white12,
        elevation: 0,
        shadowColor: Colors.white,
      ),
      body: SingleChildScrollView(
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Column(
            children: [
              Padding(
                padding: EdgeInsets.only(left: 100, top: 100, right: 100),
                child: Card(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                      topRight: Radius.circular(20),
                      topLeft: Radius.circular(20),
                      bottomLeft: Radius.circular(20),
                      bottomRight: Radius.circular(20),
                    ),
                  ),
                  child: SizedBox(
                    width: 100,
                    height: 100,
                    child: FlutterLogo(),
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 50),
                child: Text(
                  "Version $versionName",
                  style: TextStyle(fontSize: 30, color: Colors.black),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 80, left: 30, right: 30),
                child: Divider(),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 30),
                child: ListTile(
                  trailing: Icon(
                    Icons.chevron_right,
                    size: 35,
                  ),
                  title: Text(
                    "检查新版本",
                    style: TextStyle(fontSize: 25, color: Colors.black),
                  ),
                  onTap: () {
                    checkNewVersion();
                  },
                ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 30),
                child: Divider(),
              ),
              Padding(
                padding: EdgeInsets.only(top: 400),
                child: Column(
                  children: [
                    // Text(
                    //   "畅盈公司版权所有",
                    //   style: TextStyle(fontSize: 15, color: Colors.grey),
                    // ),
                    Text(
                      "Copyright © 2020-2021.",
                      style: TextStyle(fontSize: 15, color: Colors.grey),
                    ),
                    Text(
                      "All Rights Reserved.",
                      style: TextStyle(fontSize: 15, color: Colors.grey),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void checkNewVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    var version = packageInfo.version;
    var buildNumber = packageInfo.buildNumber;
    var appName = packageInfo.appName;
    var packageName = packageInfo.packageName;
    print("$appName=$packageName=$version=$buildNumber");

    try {
      executeDownload();
    } on Exception catch (e) {
      MyLog.e(e.toString());
    }
  }
}
